package com.lingjtx.iot.tsl.common;

import com.lingjtx.iot.tsl.model.BitSpecItem;
import com.lingjtx.iot.tsl.model.BitValueMapping;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class BitFieldParser {

    public static Map<String, Object> parseBinaryField(List<BitSpecItem> bitSpec, int rawValue) {
        Map<String, Object> result = new LinkedHashMap<>();

        for (BitSpecItem spec : bitSpec) {
            String identifier = spec.getIdentifier();

            // 单 bit
            if (spec.getBit() != null) {
                int bit = spec.getBit();
                boolean value = (rawValue & (1 << bit)) != 0;
                result.put(identifier, value);
            }

            // 多 bit
            else if (spec.getBits() != null && spec.getValues() != null) {
                List<Integer> bits = spec.getBits();
                StringBuilder binary = new StringBuilder();
                for (int i = bits.size() - 1; i >= 0; i--) {
                    int bit = bits.get(i);
                    binary.append(((rawValue >> bit) & 1));
                }
                String binaryStr = binary.toString();
                Integer intValue = Integer.parseInt(binaryStr, 2);

                // 匹配映射值
                String mappedName = spec.getValues().stream()
                        .filter(v -> binaryStr.equals(v.getValue()))
                        .map(BitValueMapping::getName)
                        .findFirst()
                        .orElse(binaryStr); // fallback 原始位串

                result.put(identifier, String.format("%s:%d", mappedName, intValue));
            }
        }

        return result;
    }
}
